﻿<template>
    <el-dialog
        title="调价"
        v-model="visible"
        :width="900"
        destroy-on-close
        :close-on-click-modal="false"
        :before-close="handleBeforeClose"
    >
        <el-form
            :model="entityObj"
            :rules="rules"
            :disabled="mode == 'Show'"
            ref="dialogForm"
            label-width="100px"
        >
            <el-row>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="物料编码" >
                        {{entityObj.materialCode}}
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="物料名称" >
                        {{entityObj.materialName}}
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="类别" >
                        {{entityObj.materialTypeName}}
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="物料规格" >
                        {{entityObj.materialSpecs}}
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="单位" >
                        {{entityObj.unitName}}
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="价格" > 
                        {{entityObj.price}}
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label-width="110px" label="价格表" prop="purchaseProtocolItemPrices">
                        <el-button size="small" @click="addPrice()">新增价格</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label-width="110px">
                        <el-table
                            :data="entityObj.purchaseProtocolItemPrices"
                            border
                            style="width: 100%"
                        >
                            <el-table-column label="价格" width="150">
                                <template #default="scope">
                                    <el-input-number
                                        v-model="scope.row.price"
                                        :class="{'bordered': isCurrentDateInValidityRange(scope.row.validityDates)}"
                                        style="width: 100%;"
                                        :precision="2"
                                        :step="0.00"
                                        controls-position="right"
                                    ></el-input-number>
                                </template>
                            </el-table-column>
                            <!-- <el-table-column label="回收价格" width="150">
                                <template #default="scope">
                                    <el-input-number
                                        v-model="scope.row.recoverPrice"
                                        style="width: 100%"
                                        :precision="2"
                                        :step="0.01"
                                        controls-position="right"
                                    ></el-input-number>
                                </template>
                            </el-table-column> -->
                            <!-- v-if="scope.$index>0||entityObj.purchaseProtocolItemPrices.length==1" 
                                 :disabled="scope.$index>=entityObj.purchaseProtocolItemPrices.length-1"-->
                            <el-table-column label="有效期" width="300">
                                <template #default="scope">
                                    <el-date-picker
                                        style="width: 100%"
                                        v-model="scope.row.validityDates"
                                        :class="{'bordered': isCurrentDateInValidityRange(scope.row.validityDates)}"
                                        type="datetimerange"
                                        :disabled-date="disabledDate"
                                        value-format="YYYY-MM-DD HH:mm:ss"
                                        format="YYYY-MM-DD HH:mm:ss"
                                        range-separator="-"
                                        unlink-panels="true"
                                        start-placeholder="开始时间"
                                        end-placeholder="结束时间"
                                        :clearable="false"
                                        :default-time="defaultTime"
                                        @change="(dateRange) => changeValidityDates(dateRange, scope.$index)"
                                    />
                                    <!-- <div
                                        v-if="scope.$index==0&&entityObj.purchaseProtocolItemPrices.length>1"
                                    >
                                        <el-date-picker
                                            style="width: 50%"
                                            :clearable="false"
                                            :disabled-date="disabledDate"
                                            v-model="scope.row.validityDates[0]"
                                            format="YYYY-MM-DD HH:mm:ss"
                                            @change="(date) => changeValidityDate(date, scope.$index)"
                                        />
                                        <span>至{{maxDate}}</span>
                                    </div> -->
                                </template>
                            </el-table-column>

                            <el-table-column label="操作" min-width="80">
                                <template #default="scope">
                                    <el-button
                                        size="small"
                                        @click="deleteRow(scope.$index, scope.row)"
                                    >移除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <el-button @click="handleBeforeClose">取 消</el-button>
            <el-button
                v-if="mode != 'show'"
                type="primary"
                :loading="isSaveing"
                @click="submit()"
            >保 存</el-button>
        </template>
    </el-dialog>
</template>



<script>
import tool from "@/utils/tool";
export default {
    emits: ["success", "closed"],
    data() {
        return {
            mode: "Add",
            titleMap: {
                Add: "新增",
                Edit: "编辑",
                Show: "查看",
            },
            entityObj: {
                purchaseProtocolItemPrices:[]
            },
            supplierState: false,
            applyOrderState: false,
            storeState: false,
            queryList: {},
            visible: false,
            isSaveing: false,
            needSaveFlag: false,
            //验证规则
            rules: {},
            props: {
                label: "supplierName",
                value: "supplierId",
            },
            materialProps: {
                label: "materialCode",
                value: "materialId",
                items: "materialItems",
            },
            materialTypeTree: [],
            optionsBrand: [],
            optionsUnit: [],
            optionsPurchaseUnity: [],
            itemsData: [],
            minDate: "",
            maxDate: "",
            defaultTime:[
                new Date(2000, 1, 1, 0, 0, 0),
                new Date(2000, 2, 1, 23, 59, 59),
            ]
        };
    },
    computed: {},
    methods: {
         // 判断当前日期是否在 validityDates 范围内
         isCurrentDateInValidityRange(data) {
            console.log(data);
            if (!Array.isArray(data) || data.length !== 2) {
                // 如果 data 不是数组，或长度不为 2，返回 false
                return false;
            }
            const currentDate = new Date();  // 获取当前日期时间
            const [startDate, endDate] = data;

            if (startDate && endDate) {
                // 将 startDate 和 endDate 转换为 Date 对象
                const start = new Date(startDate);
                const end = new Date(endDate);

                // 判断当前日期是否在有效日期范围内
                return currentDate >= start && currentDate <= end;
            }
            return false;  // 如果没有有效日期范围
        },
        //显示=
        async open(mode = "Add") {
            this.mode = mode;
            this.visible = true;
            return this;
        },
        handleBeforeClose() {
            this.$confirm("信息未保存,确定要关闭吗？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    this.visible = false;
                })
                .catch(() => {
                    // 用户点击了取消按钮，不执行关闭
                });
        },
        disabledDate(time) {
            return (
                time.getTime() <= new Date(this.minDate).getTime()
            );
        },
        //表单提交方法
        submit() {
            if (this.entityObj.purchaseProtocolItemPrices.some(p=>!p.validityDates[0])) {
                this.$message.error("请选择时间");
                return false;
            }

            //附属品价格可以为0
            if (this.entityObj.purchaseProtocolItemPrices.some(p=>p.price<0)) {
                this.$message.error("价格不能小等0");
                return false;
            }
            var exists = this.entityObj.purchaseProtocolItemPrices.some((p) => {
                return this.entityObj.purchaseProtocolItemPrices.some((t) => {
                    if (p !== t) {
                        // 避免与自身比较
                        if (
                            p.validityDates[0] <= t.validityDates[1] &&
                            p.validityDates[1] >= t.validityDates[0]
                        ) {
                            return true;
                        }
                    }
                    return false;
                });
            });

            if (exists) {
                this.$message.error("不能存在相同时间段的调价记录");
                return false;
            }
            this.$emit("setPrice", this.entityObj);
            this.visible = false;
        },
        //表单注入数据
        async setData(data) {
            this.entityObj = structuredClone(data);
            // this.minDate = this.entityObj.startDate;
            // this.maxDate = this.entityObj.endDate;
            // if(this.entityObj.purchaseProtocolItemPrices.length>0){
            //     this.minDate = this.entityObj.purchaseProtocolItemPrices[0].validityDates[0]; 
            // }
        },
        changeValidityDate(val, index) {
            this.entityObj.purchaseProtocolItemPrices[
                index + 1
            ].validityDates[1] = tool.getPreviousDayEndTime(val);
            this.minDate = tool.formatDate(val);
            this.entityObj.purchaseProtocolItemPrices[index].validityDates[0] =
                tool.formatDate(val);
            this.entityObj.purchaseProtocolItemPrices[index].validityDates[1] =
                this.maxDate;
        },
        changeValidityDates(val, index) {
            // if(index>0){
            //     this.entityObj.purchaseProtocolItemPrices[
            //         index - 1
            //     ].validityDates[0] = tool.getPreviousDayEndTime(val[1]);
            // }
            // this.entityObj.purchaseProtocolItemPrices[
            //     index + 1
            // ].validityDates[1] = tool.getPreviousDayEndTime(val[0]);
        },
        deleteRow(index) {
            //this.entityObj.purchaseProtocolItemPrices[index+1].validityDates[1]=this.entityObj.purchaseProtocolItemPrices[index].validityDates[1];
            this.entityObj.purchaseProtocolItemPrices.splice(index, 1);
        },
        addPrice() {
            // if (
            //     !this.entityObj.purchaseProtocolItemPrices[0].validityDates[0]
            // ) {
            //     this.$message.error("请选择时间");
            //     return false;
            // }

            //this.minDate=this.entityObj.purchaseProtocolItemPrices[0].validityDates[0];
            this.entityObj.purchaseProtocolItemPrices.unshift({
                price: "",
                validityDates: [],
                validityDate: "",
            });
        },
    },
    async mounted() {},
};
</script>

<style>
    .bordered{
        border: 1px solid green;
    }
</style>
